package logic

import (
	"context"
	"fmt"
	"srv/model/mysql"
	"srv/model/redis"

	"srv/cart"
	"srv/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type AddCartLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewAddCartLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AddCartLogic {
	return &AddCartLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *AddCartLogic) AddCart(in *cart.AddCartRequest) (*cart.AddCartResponse, error) {
	// todo: add your logic here and delete this line
	g := mysql.Good{}
	err := g.Detail(int(in.GoodId))
	if err != nil {
		logx.Error("商品信息获取失败")
		return nil, fmt.Errorf("商品信息获取失败")
	}
	if g.ID == 0 {
		logx.Error("商品不存在")
		return nil, fmt.Errorf("商品不存在")
	}
	stock := redis.GoodLLen(in.GoodId)
	if in.Num > stock {
		logx.Error("库存不足")
		return nil, fmt.Errorf("库存不足")
	}
	if redis.CartExist(in.UserId, in.GoodId) {
		err = redis.UpdateCart(in.UserId, in.GoodId, in.Num)
		if err != nil {
			logx.Error("购物车数量修改失败")
			return nil, fmt.Errorf("购物车数量修改失败")
		}
	} else {
		carts := map[string]interface{}{
			"user_id":    in.UserId,
			"good_id":    in.GoodId,
			"num":        in.Num,
			"good_title": g.GoodTitle,
			"good_price": g.GoodPrice,
			"good_state": g.GoodState,
		}
		err = redis.AddCart(carts)
		if err != nil {
			logx.Error("购物车添加失败")
			return nil, fmt.Errorf("购物车添加失败")
		}
	}
	return &cart.AddCartResponse{Success: true}, nil
}
